import storage from '@/libs/storage';
import api from '@/api';
import Vue from 'vue';
// import Router from '@/routes';
// import Hybrid from '@/components/uzone-hybrid';

export default {

  getCode() {
    const user = storage.get('user');
    return user ? user.code : '';
  },

  expireToLogin() {
    storage.remove('user');
    const $vue = new Vue();
    $vue.$hybrid.action('gotologin');
    // const hybrid = new Hybrid(this.$os.android ? 'android' : 'ios');
    // hybrid.action('endPage', {
    //   callback () {}
    // });
  },

  /**
   * 判断是否登录
   *
   * @returns
   */
  loggedIn() {
    return new Promise((resolve, reject) => {
      const code = this.getCode();
      if (!code) {
        reject();
      } else {
        resolve();
      }
    });
  },

  login(params) {
    return new Promise((resolve, reject) => {
      api.user.autoRegisterOrLogin(params).then((response) => {
        const { status, data } = response;

        if (status === '1') {
          const { code, phone, userId } = data;
          storage.set('user', {
            code,
            phone,
            userId
          });
          storage.set('expire', 24 * 60 * 60 * 1000); // 记录时间戳
          resolve();
        } else {
          reject();
        }
      });
    });
  }
};
